import { CreepRole, RoleDatas } from "@/role/types/role"
import { useCache } from "@/utils"
import { stat } from "fs"
import CreepController from "../controller"


class RoleRemoteWorker {

    static spawnRoomNames: string[] = ['E35S49', 'E39S52']
    static workRoomNames: string[][] = [['E34S48', 'E35S48'], ['E38S52']]
    static sourceIndexs: number[][][] = [[[0], [1]], [[0]]]

    // static roomNames: string[] = ['E35S48', 'E34S48']
    // static roomWorkerIndexs: number[][] = [[0], [1]]
    /**
     *
     * @param creep
     * @returns
     */
    static loop(creep: Creep) {

        // if (creep.room.name == 'E45S48') {
        //     if (creep.store[RESOURCE_ENERGY] == 0) {
        //         const container = creep.pos.findClosestByPath(FIND_STRUCTURES, {
        //             filter: s => (s.structureType == STRUCTURE_TOWER || s.structureType == STRUCTURE_EXTENSION) && s.store[RESOURCE_ENERGY] > 0
        //         }) as StructureWithStore
        //         if (container) {
        //             creep.memory.targetId = container.id
        //         }
        //     }
        //     else {
        //         const spawn = Game.getObjectById('61a21fc61b392f132e9e3a6a') as StructureSpawn
        //         if (spawn && spawn.store.getFreeCapacity(RESOURCE_ENERGY) > 0) {
        //             const status = creep.transfer(spawn, RESOURCE_ENERGY)
        //             if (status == ERR_NOT_IN_RANGE) {
        //                 creep.goTo(spawn.pos)
        //             }
        //             return
        //         }
        //     }
        // }

        // 获取creep名字后缀数字编号
        const creepIndex = parseInt(creep.name.split('_')[1])

        const spawnRoomIndex = RoleRemoteWorker.spawnRoomNames.indexOf(creep.memory.spawnRoom)
        const roomNames = RoleRemoteWorker.workRoomNames[spawnRoomIndex]
        const roomWorkerIndexs = RoleRemoteWorker.sourceIndexs[spawnRoomIndex]

        // console.log('spawnRoomIndex spawnRoom', spawnRoomIndex, creep.memory.spawnRoom, roomWorkerIndexs, roomNames, RoleRemoteWorker.roomWorkerIndexs)

        let roomName: string
        for (const index in roomWorkerIndexs) {
            const indexs = roomWorkerIndexs[index]

            for (const i in indexs) {
                if (indexs[i] == creepIndex) {
                    roomName = roomNames[index]
                    break
                }
            }
        }
        // console.log('spawnRoomIndex creepIndex roomName', spawnRoomIndex, creepIndex, roomName)


        const memoryData: RoleDatas[CreepRole.RemoteWorker] = creep.memory.data as RoleDatas[CreepRole.RemoteWorker]

        if (!memoryData) {
            creep.log('memory error')
            return
        }

        if (!memoryData.workRoom || memoryData.workRoom != roomName) {
            memoryData.workRoom = roomName
        }

        if (creep.store[RESOURCE_ENERGY] == 0 && creep.ticksToLive > 60) {

            const room = Game.rooms[memoryData.workRoom]
            if (!room || room.name != creep.room.name) {
                creep.goTo(new RoomPosition(25, 25, memoryData.workRoom))
                return
            }

            if (!creep.memory.targetId) {
                const droppedEnergy = CreepController.managerFindDropSource(creep, 50)
                if (droppedEnergy) {
                    creep.memory.targetId = droppedEnergy.id
                }
                else {
                    const container = CreepController.findContainer(creep, 50)
                    if (container) {
                        creep.memory.targetId = container.id
                    }
                }
            }

            if (creep.memory.targetId) {
                const target = Game.getObjectById(creep.memory.targetId)
                if (target) {
                    const resource = target as Resource
                    if (resource && resource.amount > 0) {
                        creep.goTo(resource.pos, { range: 1 })
                        const status = creep.pickup(resource)
                        if (status == OK) {
                            delete creep.memory.targetId
                        }
                        return
                    }

                    const container = target as StructureContainer
                    if (container && container.store[RESOURCE_ENERGY] > 0) {
                        creep.goTo(container.pos, { range: 1 })
                        const status = creep.withdraw(container, RESOURCE_ENERGY)
                        if (status == OK) {
                            delete creep.memory.targetId
                        }
                        return
                    }
                }
                delete creep.memory.targetId
                return
            }

            creep.goTo(new RoomPosition(20, 9, roomName))
        }
        else {
            if (!creep.memory.targetId && !creep.memory.repairStructureId) {
                // build
                const constructionSite = creep.room.find(FIND_CONSTRUCTION_SITES, {
                    filter: c => c.my
                })[0] as ConstructionSite
                if (constructionSite) {
                    creep.memory.targetId = constructionSite.id
                }
            }

            if (!creep.memory.targetId && !creep.memory.repairStructureId) {
                // 找到受损建筑
                const target: AnyStructure = useCache(() => {
                    const damagedStructures = creep.room.find(FIND_STRUCTURES, {
                        filter: s => s.hits < s.hitsMax &&
                            // 墙壁在刷墙任务里维护
                            s.structureType != STRUCTURE_RAMPART &&
                            s.structureType != STRUCTURE_WALL
                        //  && s.structureType != STRUCTURE_ROAD
                    })
                    // 找到最近的受损建筑并更新缓存
                    if (damagedStructures.length > 0) return creep.pos.findClosestByRange(damagedStructures)
                }, creep.memory, 'repairStructureId')
                // 没有需要维修的建筑，任务完成
                if (!target) {
                    delete creep.memory.repairStructureId
                }
                else {
                    creep.memory.repairStructureId = target.id
                }
            }

            if (creep.memory.targetId) {
                let constructionSite: ConstructionSite;
                constructionSite = Game.getObjectById(creep.memory.targetId) as ConstructionSite
                if (!constructionSite) {
                    delete creep.memory.targetId
                }
                if (constructionSite) {
                    const status = creep.build(constructionSite)
                    if (status == ERR_NOT_IN_RANGE) {
                        creep.goTo(constructionSite.pos)
                        creep.say('W->B')
                    }
                    else if (status == ERR_INVALID_TARGET || status == OK) {
                        delete creep.memory.targetId
                    }
                    return
                }
            }

            if (creep.memory.repairStructureId) {
                // 修满了就换建筑
                const target = Game.getObjectById(creep.memory.repairStructureId)
                if (!target) {
                    delete creep.memory.repairStructureId
                }

                if (target.hits >= target.hitsMax) {
                    delete creep.memory.repairStructureId
                }
                creep.say('W->R')
                creep.goTo(target.pos)
                const status = creep.repair(target)
                if (status == OK) {
                    delete creep.memory.repairStructureId
                }
                return
            }

            creep.goTo(new RoomPosition(20, 9, roomName))
        }
    }
}

export default RoleRemoteWorker
